package com.dhcc.cdc.util;

import cn.hutool.json.JSONUtil;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.core.framework.util.SpringContextHolder;
import com.dhcc.core.modules.system.cache.config.ConfigCache;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.*;
import org.pentaho.di.core.plugins.PluginFolder;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0 DHCC-SDS
 * @Description: Kettle工具类
 * @Project Name:
 * @Package Name:
 * @File Name:KettleUtil
 * @author:sunyingjie-医务管理
 * @date: 2019年8月29日 上午9:34:45
 * @Copyright: (c) DHCC All rights reserved.
 */
public class KettleUtil {
	
	protected final static Logger logger = LoggerFactory.getLogger(KettleUtil.class);
    private static JdbcTemplate jdbcTemplate = SpringContextHolder.getBean(JdbcTemplate.class);
    private static final String pluginsPath = "kettle" + File.separator + "plugins";
    private static final String ktrPath = "kettle" + File.separator + "ktr" + File.separator;
    private static final String kjbPath = "kettle" + File.separator + "syndata" + File.separator;
    private static final String irisPath = "kettle" + File.separator + "iris" + File.separator + "ktr" + File.separator;
    private static final SysProperties sysProperties = SpringContextHolder.getBean(SysProperties.class);

    public static String runStatus = "";
    public static String logString = "";
    /**
     * @Description: 启动kettle的job
     * @Title: runJob
     * @param fileName
     * @author： sunyingjie
     * @date:  2019年8月29日 上午9:34:45
     */
    public static void runJob(String fileName) throws KettleException{

        String jobFile = fileName;
        // 初始化
        KettleEnvironment.init();
        // 任务元对象
        JobMeta jm = new JobMeta(jobFile,null);
        // 任务
        Job job = new Job(null,jm);
        // 传参
        //jm.setParameterValue("PATIENT_ID", id);
        // 开始任务
        job.start();
        // 等待任务结束
        job.waitUntilFinished();

        logger.info("job结果："+job.getResult());
    }

    public static void runPaAdmJob(String id,String fileName,int PaadmByIdTimeOut) throws KettleException{

        String jobFile = fileName;
        // 初始化
        KettleEnvironment.init();
        // 任务元对象
        JobMeta jm = new JobMeta(jobFile,null);
        // 任务
        Job job = new Job(null,jm);
        // 传参
        jm.setParameterValue("PATIENT_ID", id);
        //jm.setVariable("PATIENT_ID", id);
        // 开始任务
        job.start();
        // 等待任务结束
        // job.waitUntilFinished();
        job.waitUntilFinished(PaadmByIdTimeOut*1000);

        logger.info("++++病例"+id+"的job结果："+job.getResult());
    }

    /**
     * @Description: 启动kettle的trans
     * @Title: runTrans
     * @param id
     * @throws KettleException
     * @author： sunyingjie
     * @date:  2019年8月29日 上午9:34:45
     */
    public static void runPaAdmTrans(String id,String fileName) throws KettleException{
        String transFile = fileName;
        // 初始化
        KettleEnvironment.init();
        // 转换元对象
        TransMeta tm = new TransMeta(transFile);
        // 转换
        Trans trans = new Trans(tm);
        // 传参
        trans.setVariable("PATIENT_ID", id);
        // 执行转换
        trans.execute(null);
        // 等待转换执行结束
        trans.waitUntilFinished();
    }

    /**
     * 执行sds数据抽取job
     *
     * @param fileName   文件名称
     * @param beginTime  开始时间
     * @param endTime    结束时间
     * @param episodeId  就诊号
     * @param isSynBase       抽取种类
     * @param initialize 是否抽取患者全部数据
     * @return
     */
    public static Boolean runSDSJob(String fileName, Map<String, Object> variableMap, String beginTime, String endTime, String episodeId, String isSynBase, boolean initialize) throws KettleException {
        runStatus = "start";
        String jobFile = sysProperties.getSysHome() + kjbPath + fileName;
        //设置本地插件
        // StepPluginType.getInstance().getPluginFolders().add(new PluginFolder(sysProperties.getSysHome() + pluginsPath, false, true));
        // 初始化
        if (!KettleEnvironment.isInitialized()) {
            KettleEnvironment.init();
        }
        // 任务元对象
        JobMeta jm = new JobMeta(jobFile, null);
        // 任务
        Job job = new Job(null, jm);

        // 传参
        job.setVariable("beginTime", beginTime);
        job.setVariable("endTime", endTime);
        job.setVariable("episodeId", episodeId);
        job.setVariable("isSynBase", isSynBase);

        if (initialize) {
            job.setVariable("defaultBeginTime", "");
            job.setVariable("defaultEndTime", "");
        } else {
            job.setVariable("defaultBeginTime", beginTime);
            job.setVariable("defaultEndTime", endTime);
        }

        String type = "2";
        if (CommonUtil.isNotEmpty(episodeId)) {
            type = "1";
        } else{
            type = "2";
        }
        job.setVariable("type", type);

        // 参入kettle额外参数（数据库连接配置等）
        variableMap.forEach((key, value) ->{
            job.setVariable(key, String.valueOf(value));
        });
        // 作业日志级别
        job.setLogLevel(LogLevel.BASIC);

        // 添加运行日志监听
        KettleLoggingEventListener kettleLogEL = logs -> {
            //logs为kettle运行时输出的日志。
            logString += DateUtil.getTime() + "-" + logs.getMessage().toString()+"<br>";
            int len = logString.length();
            logString = len>100000?logString.substring(len - 100000):logString;
        };
        KettleLogStore.getAppender().addLoggingEventListener(kettleLogEL);
        // 开始任务
        job.start();
        // 等待任务结束
        job.waitUntilFinished();
        // 删除运行日志监听
        KettleLogStore.getAppender().clear();// 该方法不起作用，原因暂未查找
        KettleLogStore.getAppender().removeLoggingEventListener(kettleLogEL);// 删除运行日志监听

        runStatus = "end";

        if (job.getErrors() > 0) {
            return false;
        }
        return true;
    }


    public static Map<String, Object> getLogs() {
        Map<String, Object> state = new HashMap<String, Object>();
        if (CommonUtil.equals(runStatus, "end")) {//没有获取到数据
            state.put("v", logString);//值
            state.put("i", "end");//信息
            logString = "";
        } else {
            state.put("v", logString);//值
            state.put("i", "ing");//信息
        }
        return state;
    }
}
